<template>
  <div class="search-team-container">
    <!-- 顶部导航 -->
    <header class="header">
      <button class="back-btn" @click="goBack">
        <span class="back-icon">‹</span>
        搜索队伍
      </button>
    </header>

    <!-- 主要内容 -->
    <main class="main-content">
      <!-- 页面标题 -->
      <h1 class="page-title">搜索队伍</h1>
      
      <!-- 搜索功能 -->
      <div class="search-section">
        <div class="search-container">
          <input 
            v-model="searchKeyword" 
            type="text" 
            placeholder="可以搜索队伍名称、队伍编号"
            class="search-input"
            @input="handleSearch"
            @keyup.enter="handleSearch"
          />
          <button class="search-btn" @click="handleSearch">🔍</button>
        </div>
      </div>

      <!-- 队伍列表 -->
      <div class="team-list">
        <div class="list-header">
          <div class="header-item">队伍名称</div>
          <div class="header-item">队伍编号</div>
          <div class="header-item">成员数</div>
          <div class="header-item">指导老师</div>
          <div class="header-item">入驻</div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <div class="loading-text">正在搜索队伍信息...</div>
        </div>

        <!-- 队伍列表项 -->
        <div v-else class="team-items">
          <div 
            v-for="team in teams" 
            :key="team.teamId"
            class="team-item"
          >
            <div class="team-info">
              <span class="team-name">{{ team.teamName }}</span>
            </div>
            <div class="team-info">
              <span class="team-number">{{ team.teamCode }}</span>
            </div>
            <div class="team-info">
              <span class="team-member-count">{{ team.memberCount }}</span>
            </div>
            <div class="team-info">
              <span class="team-advisor">{{ team.advisorName }}</span>
            </div>
            <div class="team-action">
              <button 
                class="join-btn"
                :class="{ 'joined': team.isJoined, 'recommended': team.isRecommended }"
                @click="toggleJoinTeam(team)"
                :disabled="team.isJoined"
              >
                <span class="star-icon">{{ team.isJoined ? '★' : (team.isRecommended ? '★' : '☆') }}</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && teams.length === 0" class="empty-state">
          <div class="empty-icon">🔍</div>
          <div class="empty-text">暂无符合条件的队伍</div>
          <div class="empty-hint">请尝试调整搜索条件</div>
        </div>
      </div>
    </main>

    <!-- 入驻确认弹窗 -->
    <div v-if="showJoinModal" class="modal-overlay" @click="closeJoinModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认入驻</h3>
          <button class="close-btn" @click="closeJoinModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="join-icon">⭐</div>
          </div>
          <p class="modal-text">确定要入驻队伍"{{ selectedTeam?.teamName }}"吗？</p>
          <p class="modal-subtitle">入驻后您将成为该队伍的专家成员</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeJoinModal" :disabled="joining">取消</button>
          <button class="confirm-btn" @click="confirmJoinTeam" :disabled="joining">
            {{ joining ? '入驻中...' : '确认入驻' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 消息提示弹窗 -->
    <div v-if="showMessageModal" class="modal-overlay" @click="closeMessageModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header" :class="messageType === 'success' ? 'success-header' : 'error-header'">
          <h3>{{ messageTitle }}</h3>
          <button class="close-btn" @click="closeMessageModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="message-icon" :class="messageType === 'success' ? 'success-icon' : 'error-icon'">
              {{ messageType === 'success' ? '✓' : '✗' }}
            </div>
          </div>
          <p class="modal-text">{{ messageText }}</p>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeMessageModal">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getAllTeamsService, joinTeamAsExpertService, searchTeamsService } from '@/api/team.js'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('') // 搜索关键词
const loading = ref(false) // 加载状态
const showJoinModal = ref(false) // 入驻确认弹窗
const selectedTeam = ref(null) // 选中的队伍
const joining = ref(false) // 入驻处理状态

// 消息提示相关
const showMessageModal = ref(false)
const messageTitle = ref('')
const messageText = ref('')
const messageType = ref('success') // success | error

// 队伍数据（从API获取）
const teams = ref([])

// 页面挂载时的初始化
onMounted(() => {
  loadTeams()
})

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 加载队伍数据
const loadTeams = async () => {
  loading.value = true
  try {
    const result = await getAllTeamsService()
    if (result.code === 200) {
      // 为每个队伍添加入驻状态相关字段
      teams.value = result.data.map(team => ({
        ...team,
        isJoined: team.roleInTeam === 'expert', // 如果角色是专家，说明已入驻
        isRecommended: false, // 可以根据实际业务逻辑设置推荐状态
        memberCount: `${team.currentMembers || 0}/${team.maxMembers || 30}`, // 成员数量显示
        advisorName: team.instructorName || '未知' // 指导老师姓名
      }))
      
      // 调试信息：检查入驻状态
      const joinedTeams = teams.value.filter(team => team.isJoined)
      console.log('当前已入驻的队伍数量:', joinedTeams.length)
      console.log('已入驻的队伍:', joinedTeams.map(t => ({ name: t.teamName, role: t.roleInTeam })))
      
      console.log('队伍数据加载成功:', teams.value)
    } else {
      console.error('加载队伍数据失败:', result.msg)
      showErrorMessage(result.msg || '加载队伍数据失败')
    }
  } catch (error) {
    console.error('加载队伍数据异常:', error)
    showErrorMessage('加载队伍数据时发生错误')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = async () => {
  const keyword = searchKeyword.value.trim()
  console.log('搜索队伍关键词:', keyword)
  
  loading.value = true
  try {
    let result
    if (keyword) {
      // 有搜索关键词，调用搜索API
      result = await searchTeamsService(keyword)
    } else {
      // 无搜索关键词，获取所有队伍
      result = await getAllTeamsService()
    }
    
    if (result.code === 200) {
      // 为每个队伍添加入驻状态相关字段
      teams.value = result.data.map(team => ({
        ...team,
        isJoined: team.roleInTeam === 'expert', // 如果角色是专家，说明已入驻
        isRecommended: false, // 可以根据实际业务逻辑设置推荐状态
        memberCount: `${team.currentMembers || 0}/${team.maxMembers || 30}`, // 成员数量显示
        advisorName: team.instructorName || '未知' // 指导老师姓名
      }))
      
      console.log(`搜索结果(${keyword || '全部'})：`, teams.value.length, '个队伍')
    } else {
      console.error('搜索队伍失败:', result.msg)
      showErrorMessage(result.msg || '搜索队伍失败')
      teams.value = []
    }
  } catch (error) {
    console.error('搜索队伍异常:', error)
    showErrorMessage('搜索队伍时发生错误')
    teams.value = []
  } finally {
    loading.value = false
  }
}

// 切换入驻队伍状态
const toggleJoinTeam = (team) => {
  if (team.isJoined) {
    return // 已入驻的不能再操作
  }
  
  selectedTeam.value = team
  showJoinModal.value = true
}

// 关闭入驻确认弹窗
const closeJoinModal = () => {
  showJoinModal.value = false
  // 延迟清空选中的队伍，避免引用问题
  setTimeout(() => {
    selectedTeam.value = null
  }, 100)
}

// 确认入驻队伍
const confirmJoinTeam = async () => {
  if (!selectedTeam.value) return
  
  joining.value = true // 开始入驻处理
  // 保存队伍名称，避免后续selectedTeam被清空后无法访问
  const teamName = selectedTeam.value.teamName
  
  try {
    const result = await joinTeamAsExpertService(selectedTeam.value.teamId)
    if (result.code === 200) {
      // 立即更新队伍状态（优化用户体验）
      const teamIndex = teams.value.findIndex(team => team.teamId === selectedTeam.value.teamId)
      if (teamIndex !== -1) {
        console.log('更新前的队伍状态:', {
          teamName: teams.value[teamIndex].teamName,
          isJoined: teams.value[teamIndex].isJoined,
          roleInTeam: teams.value[teamIndex].roleInTeam
        })
        
        teams.value[teamIndex].isJoined = true
        teams.value[teamIndex].roleInTeam = 'expert' // 确保角色是专家
        
        console.log('更新后的队伍状态:', {
          teamName: teams.value[teamIndex].teamName,
          isJoined: teams.value[teamIndex].isJoined,
          roleInTeam: teams.value[teamIndex].roleInTeam
        })
      }
      
      closeJoinModal()
      showSuccessMessage(`成功入驻队伍"${teamName}"`)
      
      // 异步重新加载队伍列表以确保状态完全同步
      loadTeams().catch(error => {
        console.error('重新加载队伍列表失败:', error)
      })
      
      console.log('入驻队伍成功:', selectedTeam.value)
    } else {
      console.error('入驻队伍失败:', result.msg)
      // 根据错误信息提供更友好的提示
      let errorMessage = result.msg || '入驻失败，请稍后重试'
      if (result.msg && result.msg.includes('不能入驻自己创建的队伍')) {
        errorMessage = '不能入驻自己创建的队伍'
      } else if (result.msg && result.msg.includes('已经入驻该队伍')) {
        errorMessage = '您已经入驻该队伍，无需重复操作'
      } else if (result.msg && result.msg.includes('队伍不存在')) {
        errorMessage = '队伍不存在或已解散'
      } else if (result.msg && result.msg.includes('队伍状态异常')) {
        errorMessage = '队伍状态异常，无法入驻'
      }
      showErrorMessage(errorMessage)
    }
  } catch (error) {
    console.error('入驻队伍异常:', error)
    let errorMessage = '入驻失败，请稍后重试'
    
    // 检查 error 对象本身是否包含错误信息（axios响应拦截器处理后的格式）
    if (error.msg) {
      errorMessage = error.msg
      // 根据具体错误信息提供更友好的提示
      if (error.msg.includes('不能入驻自己创建的队伍')) {
        errorMessage = '不能入驻自己创建的队伍'
      } else if (error.msg.includes('已经入驻该队伍')) {
        errorMessage = '您已经入驻该队伍，无需重复操作'
      } else if (error.msg.includes('队伍不存在')) {
        errorMessage = '队伍不存在或已解散'
      } else if (error.msg.includes('队伍状态异常')) {
        errorMessage = '队伍状态异常，无法入驻'
      }
    } else if (error.response && error.response.data && error.response.data.msg) {
      // 处理标准axios错误响应格式
      errorMessage = error.response.data.msg
    }
    
    showErrorMessage(errorMessage)
  } finally {
    joining.value = false // 结束入驻处理
  }
}

// 显示成功消息
const showSuccessMessage = (text) => {
  messageTitle.value = '入驻成功'
  messageText.value = text
  messageType.value = 'success'
  showMessageModal.value = true
}

// 显示错误消息
const showErrorMessage = (text) => {
  messageTitle.value = '操作失败'
  messageText.value = text
  messageType.value = 'error'
  showMessageModal.value = true
}

// 关闭消息弹窗
const closeMessageModal = () => {
  showMessageModal.value = false
}
</script>

<style scoped lang="scss">
@import '@/assets/css/search-team.css';
</style> 